package com.kfm.service;

import com.kfm.dao.FileDao;
import com.kfm.model.FileDO;
import com.kfm.model.FileDTO;
import com.kfm.util.Contains;
import com.kfm.util.UUIDUtil;

import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.List;

public class FileService {

    private FileDao fileDao = new FileDao();

    public int save(Part part, int accountId){

        String fileName = part.getSubmittedFileName();
        long size = part.getSize();
        // 保存的文件名
        String sub = fileName.substring(fileName.lastIndexOf("."));
        String saveName = UUIDUtil.uuid32() + sub;

        // 保存的目录
        String date = LocalDate.now().toString().replace("-", "");
        File directory = new File(Contains.FILE_PATH, date);

        // 目录不存在则创建
        if (!directory.exists()){
            directory.mkdirs();
        }
        File saveFile = new File(directory, saveName);
        try {
            // 保存
            part.write(saveFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 存数据库
        FileDO fileDO = new FileDO();

        fileDO.setName(fileName);
//        fileDO.setPath(saveFile.getAbsolutePath());
        fileDO.setPath(date + File.separator + saveName);

        fileDO.setUrl("");
        fileDO.setSize(size);
        fileDO.setCreateAccount(accountId);

        int id = fileDao.saveWithKey(fileDO);

        // 更新 url
        return fileDao.updateUrlById(id, "download?id=" + id);
    }

    public FileDO queryById(Integer id){
        if (id != null){
            return fileDao.selectById(id);
        }
        return null;
    }

    public List<FileDO> queryAll(){
        return fileDao.selectAll();
    }

    public List<FileDTO> queryAllWithAccount(){
        return fileDao.selectAllWithUsername();
    }
}
